import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:meco/common/index.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:meco/views/index.dart';

import 'index.dart';

class OfficialPage extends GetView<OfficialController> {
  const OfficialPage({super.key});

  // 主视图
  Widget _buildView() {
    return Obx(() {
      final content = controller.content.value;

      if (content == null) {
        return Center(child: CircularProgressIndicator());
      }

      return LayoutBuilder(
        builder: (context, constraints) {
          return NotificationListener<DraggableScrollableNotification>(
            onNotification: (notification) {
              controller.updateDragRatio(notification.extent);
              return true;
            },
            child: Stack(
              children: [
                // 背景图片
                Obx(() {
                  // 计算图片高度：总高度 * (1 - 拖拽比例)，最小保持20%可见
                  final imageHeight =
                      constraints.maxHeight *
                      (1.0 - controller.dragRatio.value) *
                      1.2;

                  return Positioned(
                    top: 0,
                    left: 0,
                    right: 0,
                    height: imageHeight,
                    child: Container(
                      clipBehavior: Clip.hardEdge,
                      decoration: BoxDecoration(),
                      child:
                          content.imageUrl != null
                              ? Image.asset(
                                content.imageUrl!,
                                fit: BoxFit.cover,
                              )
                              : Container(
                                color: Colors.grey[300],
                                child: Icon(
                                  Icons.image_not_supported,
                                  size: 50.sp,
                                  color: Colors.grey[500],
                                ),
                              ),
                    ),
                  );
                }),

                // 导航栏
                Positioned(
                  top: MediaQuery.of(Get.context!).padding.top,
                  left: 0,
                  right: 0,
                  child: Padding(
                    padding: EdgeInsets.symmetric(
                      horizontal: 16.w,
                      vertical: 10.h,
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        // 返回按钮
                        GestureDetector(
                          onTap: () => Get.back(),
                          child: Icon(
                            IconFontIcons.iconBack,
                            color: Colors.white,
                            size: 24.sp,
                          ),
                        ),

                        // 页面标题
                        Text(
                          'Recommended details',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 20.sp,
                            fontWeight: FontWeight.w600,
                            shadows: [
                              Shadow(
                                offset: Offset(1, 1),
                                blurRadius: 3.0,
                                color: Colors.black.withOpacity(0.5),
                              ),
                            ],
                          ),
                        ),

                        // 举报按钮
                        GestureDetector(
                          onTap: () => controller.reportOfficialContent(),
                          child: Icon(
                            IconFontIcons.iconReport,
                            color: Colors.white,
                            size: 28.sp,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),

                // 可拖拽的内容区域
                DraggableScrollableSheet(
                  initialChildSize: 0.5,
                  minChildSize: 0.2,
                  maxChildSize: 0.85,
                  builder: (context, scrollController) {
                    return Stack(
                      clipBehavior: Clip.none,
                      children: [
                        // 主容器
                        Container(
                          height: double.infinity,
                          decoration: BoxDecoration(
                            color: Colors.white,
                            image: DecorationImage(
                              image: AssetImage(Images.startBg),
                              fit: BoxFit.cover,
                            ),
                            borderRadius: BorderRadius.vertical(
                              top: Radius.circular(24.r),
                            ),
                            boxShadow: [
                              BoxShadow(
                                color: Colors.black.withOpacity(0.1),
                                blurRadius: 10,
                                spreadRadius: 0,
                              ),
                            ],
                          ),
                          child: SingleChildScrollView(
                            controller: scrollController,
                            child: Padding(
                              padding: EdgeInsets.only(
                                left: 24.r,
                                right: 24.r,
                                bottom: 24.r,
                                top: 32.r,
                              ),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  SizedBox(height: 20.h),
                                  // 标题
                                  Text(
                                    'Unique craftsmanship',
                                    style: TextStyle(
                                      color: Colors.white,
                                      fontSize: 20.sp,
                                      fontWeight: FontWeight.w600,
                                    ),
                                  ),

                                  SizedBox(height: 20.h),

                                  // 描述内容
                                  Text(
                                    'After being tempered at 1300℃, this is not only an artifact, but also a period of elegant time precipitation. Every glaze pattern is a unique surprise.',
                                    style: TextStyle(
                                      color: Colors.white,
                                      fontSize: 15.sp,
                                      fontFamily: 'Inter',
                                      fontWeight: FontWeight.w400,
                                      height: 1.60,
                                    ),
                                  ),

                                  SizedBox(height: 20.h),

                                  // 浏览用户头像组件
                                  _buildViewedUsers(),

                                  SizedBox(height: 20.h),

                                  Divider(
                                    color: Colors.white.withValues(alpha: 36),
                                    height: 1,
                                  ),

                                  // 评论列表
                                  _buildCommentList(),

                                  // 为了确保内容可以滚动，添加一些额外的空间
                                  SizedBox(height: 80.h),
                                ],
                              ),
                            ),
                          ),
                        ),

                        // 跨边界标题
                        Positioned(
                          top: -28.h,
                          left: 0,
                          right: 0,
                          child: Center(
                            child: Container(
                              width: 221.w,
                              height: 56.h,
                              decoration: ShapeDecoration(
                                gradient: LinearGradient(
                                  begin: Alignment(0.50, -0.00),
                                  end: Alignment(0.50, 1.00),
                                  colors: [
                                    const Color(0xFF4580DD),
                                    const Color(0xFF5592F1),
                                  ],
                                ),
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(33.50.r),
                                ),
                              ),
                              child: Center(
                                child: Text(
                                  'Official Recommendation',
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 16.sp,
                                    fontWeight: FontWeight.w400,
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ),
                      ],
                    );
                  },
                ),
              ],
            ),
          );
        },
      );
    });
  }

  // 构建评论列表
  Widget _buildCommentList() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 评论标题区域
        Padding(
          padding: EdgeInsets.symmetric(vertical: 16.h),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                'Comments',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 18.sp,
                  fontWeight: FontWeight.w600,
                ),
              ),
              Obx(
                () => Text(
                  '${controller.comments.length} comments',
                  style: TextStyle(color: Colors.white70, fontSize: 14.sp),
                ),
              ),
            ],
          ),
        ),

        // 评论列表
        Obx(() {
          if (controller.isLoadingComments.value) {
            return SizedBox(
              height: 100.h,
              child: Center(
                child: CircularProgressIndicator(
                  color: Colors.white,
                  strokeWidth: 2,
                ),
              ),
            );
          }

          if (controller.comments.isEmpty) {
            return SizedBox(
              height: 100.h,
              child: Center(
                child: Text(
                  'Be the first to comment',
                  style: TextStyle(color: Colors.white70, fontSize: 16.sp),
                ),
              ),
            );
          }

          return ListView.separated(
            physics: NeverScrollableScrollPhysics(),
            padding: EdgeInsets.zero,
            shrinkWrap: true,
            itemCount: controller.comments.length,
            separatorBuilder: (context, index) => SizedBox(height: 16.h),
            itemBuilder: (context, index) {
              final comment = controller.comments[index];
              return _buildCommentItem(comment);
            },
          );
        }),
      ],
    );
  }

  // 构建单个评论项
  Widget _buildCommentItem(CommentModel comment) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 用户头像和名称
            Row(
              children: [
                // 用户头像
                GestureDetector(
                  onTap: () {
                    // 先尝试删除已存在的MeController实例，再跳转
                    try {
                      if (Get.isRegistered<MeController>()) {
                        Get.delete<MeController>(force: true);
                      }
                    } catch (e) {
                      print('删除MeController失败: $e');
                    }
                    Get.toNamed(
                      Routes.me,
                      arguments: {
                        'userId': int.tryParse(comment.userId),
                        'fromNavBar': false,
                        'forceRefresh': true,
                      },
                    );
                  },
                  child: Container(
                    height: 42.h,
                    width: 42.w,
                    decoration: BoxDecoration(shape: BoxShape.circle),
                    child: ClipOval(
                      child:
                          comment.userAvatar.isNotEmpty
                              ? Image.asset(
                                comment.userAvatar,
                                fit: BoxFit.cover,
                              )
                              : Container(
                                color: Colors.grey[300],
                                child: Icon(
                                  Icons.person,
                                  size: 20.sp,
                                  color: Colors.grey[600],
                                ),
                              ),
                    ),
                  ),
                ),
                SizedBox(width: 10.w),
                // 用户名
                Text(
                  comment.userName,
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 14.sp,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ],
            ),

            // 举报按钮
            GestureDetector(
              onTap: () {
                // 处理举报逻辑
                controller.reportComment(comment);
              },
              child: Icon(
                IconFontIcons.iconFrame,
                color: Colors.white70,
                size: 18.sp,
              ),
            ),
          ],
        ),

        SizedBox(height: 8.h),

        // 评论内容
        Text(
          comment.content,
          style: TextStyle(
            color: const Color(0xFFD1D1D1),
            fontSize: 14.sp,
            fontFamily: 'Inter',
            fontWeight: FontWeight.w400,
            height: 1.5,
          ),
        ),

        SizedBox(height: 8.h),

        // 评论时间
        Text(
          _formatDateTime(comment.createdAt),
          style: TextStyle(
            color: Colors.white54,
            fontSize: 12.sp,
            fontFamily: 'Inter',
            fontWeight: FontWeight.w400,
          ),
        ),
      ],
    );
  }

  // 格式化日期时间英文
  String _formatDateTime(DateTime dateTime) {
    final now = DateTime.now();
    final difference = now.difference(dateTime);

    if (difference.inDays > 365) {
      return '${difference.inDays ~/ 365} years ago';
    } else if (difference.inDays > 30) {
      return '${difference.inDays ~/ 30} months ago';
    } else if (difference.inDays > 0) {
      return '${difference.inDays} days ago';
    } else if (difference.inHours > 0) {
      return '${difference.inHours} hours ago';
    } else if (difference.inMinutes > 0) {
      return '${difference.inMinutes} minutes ago';
    } else {
      return 'just now';
    }
  }

  // 构建浏览用户头像组件
  Widget _buildViewedUsers() {
    return Obx(() {
      final isLoading = controller.isLoadingUsers.value;
      final viewedUsers = controller.viewedUsers;

      if (isLoading) {
        return SizedBox(
          height: 50.h,
          child: Center(
            child: SizedBox(
              width: 20.w,
              height: 20.h,
              child: CircularProgressIndicator(
                strokeWidth: 2.0,
                color: Colors.white,
              ),
            ),
          ),
        );
      }

      return Row(
        children: [
          // 浏览用户头像
          if (viewedUsers.isNotEmpty) ...[
            SizedBox(
              height: 44.h,
              width: viewedUsers.length > 1 ? 30.w * viewedUsers.length : 44.w,
              child: Stack(
                children: List.generate(
                  viewedUsers.length > 5 ? 5 : viewedUsers.length,
                  (index) => Positioned(
                    left: index * 20.w,
                    child: Container(
                      height: 44.h,
                      width: 44.w,
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        border: Border.all(color: Colors.white, width: 2),
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black.withOpacity(0.1),
                            blurRadius: 4,
                            spreadRadius: 1,
                          ),
                        ],
                      ),
                      child: ClipOval(
                        child:
                            viewedUsers[index].avatar != null
                                ? Image.asset(
                                  viewedUsers[index].avatar!,
                                  fit: BoxFit.cover,
                                )
                                : Container(
                                  color: Colors.grey[300],
                                  child: Icon(
                                    Icons.person,
                                    size: 25.sp,
                                    color: Colors.grey[600],
                                  ),
                                ),
                      ),
                    ),
                  ),
                ),
              ),
            ),
            SizedBox(width: 10.w),
            Text(
              'Already viewed',
              style: TextStyle(
                color: Colors.white70,
                fontSize: 14.sp,
                fontWeight: FontWeight.w400,
              ),
            ),
          ] else ...[
            // 没有浏览用户时显示
            Container(
              height: 40.h,
              width: 40.w,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                border: Border.all(color: Colors.white, width: 2),
              ),
              child: Center(
                child: Icon(Icons.add, size: 20.sp, color: Colors.white),
              ),
            ),
            SizedBox(width: 10.w),
            Text(
              'No one viewed',
              style: TextStyle(
                color: Colors.white70,
                fontSize: 14.sp,
                fontWeight: FontWeight.w400,
              ),
            ),
          ],
        ],
      );
    });
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<OfficialController>(
      init: OfficialController(),
      id: "official",
      builder: (_) {
        return Scaffold(
          extendBodyBehindAppBar: true,
          extendBody: true,
          appBar: PreferredSize(
            preferredSize: Size.fromHeight(0),
            child: AppBar(
              backgroundColor: Colors.transparent,
              elevation: 0,
              systemOverlayStyle: SystemUiOverlayStyle.light, // 状态栏文字为白色
            ),
          ),
          body: _buildView(),
          bottomSheet: _buildCommentInput(context),
        );
      },
    );
  }

  // 评论输入区域
  Widget _buildCommentInput(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(top: 2.h),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(30.r),
          topRight: Radius.circular(30.r),
        ),
      ),
      child: SafeArea(
        child: Container(
          padding: EdgeInsets.only(
            left: 20.w,
            right: 20.w,
            top: 24.h,
            bottom: 36.h,
          ),
          decoration: BoxDecoration(
            color: const Color(0xFF08306F),
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(28.r),
              topRight: Radius.circular(28.r),
            ),
          ),
          child: Row(
            children: [
              // 评论输入框
              Expanded(
                child: Container(
                  padding: EdgeInsets.symmetric(horizontal: 16.w),
                  decoration: BoxDecoration(
                    color: Colors.white.withOpacity(0.51),
                    borderRadius: BorderRadius.circular(26.r),
                  ),
                  child: TextField(
                    controller: controller.commentController,
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 14.sp,
                      fontFamily: 'Inter',
                      fontWeight: FontWeight.w400,
                    ),
                    decoration: InputDecoration(
                      hintText: 'Say something...',
                      hintStyle: TextStyle(
                        color: Colors.white,
                        fontSize: 14.sp,
                        fontFamily: 'Inter',
                        fontWeight: FontWeight.w400,
                      ),
                      border: InputBorder.none,
                      contentPadding: EdgeInsets.symmetric(vertical: 10.h),
                    ),
                  ),
                ),
              ),

              // 发送按钮
              SizedBox(width: 8.w),
              InkWell(
                onTap: () {
                  controller.addComment();
                  // 隐藏键盘
                  FocusScope.of(context).unfocus();
                },
                child: Container(
                  width: 96.w,
                  height: 52.h,
                  decoration: ShapeDecoration(
                    color: Colors.white.withValues(alpha: 0.51),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(26.r),
                    ),
                  ),
                  child: Center(
                    child: Text(
                      'Send',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 17.sp,
                        fontWeight: FontWeight.w400,
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
